package myky.com.doctorapp.base;

import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;

import java.net.ConnectException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import myky.com.doctorapp.entity.PageEntity;

/**
 * 封装Subscribe订阅对象 统一处理回调码
 */

public abstract class RxPageSubscribe<T> implements Observer<BaseEntity<T>> {


    public RxPageSubscribe() {
    }

    protected abstract void onSuccess(T t, PageEntity pageEntity);


    protected abstract void onFailed(int code, String msg);


    @Override
    public abstract void onSubscribe(@NonNull Disposable d);

    @Override
    public void onComplete() {
        // 比如隐藏加载中对话框
    }

    @Override
    public void onNext(BaseEntity<T> baseModel) {

        PageEntity pageEntity = new PageEntity();
        pageEntity.setCurrent(baseModel.getCurrent());
        pageEntity.setTotal(baseModel.getTotal());
        pageEntity.setSize(baseModel.getSize());
        pageEntity.setPages(baseModel.getPages());
        pageEntity.setVersion(baseModel.getVersion());

        Integer resultCode = null;
        if (baseModel.type != null) {
            onSuccess(baseModel.payLoad, pageEntity);

        } else if (baseModel.code != null) {
            resultCode = baseModel.code;
            if (resultCode == 1) {
                onSuccess(baseModel.data, pageEntity);
            }
        } else {
            onFailed(baseModel.type, baseModel.msg);
        }
    }

    @Override
    public void onError(Throwable t) {
        if (t instanceof ConnectException) {
            //网络连接失败
            onFailed(403, t.getMessage());
        } else if (t instanceof HttpException) {
            HttpException ex = (HttpException) t;
            onFailed(ex.code(), ex.message());
        } else {
            onFailed(405, t.getMessage());
        }
    }
}
